<template>
  <view class="page">
    <!-- 页面内容区域 -->
    <view class="content">
      <!-- 登录状态检查 -->
      <view v-if="!isLoggedIn" class="login-prompt">
        <view class="prompt-icon">
          <uni-icons type="person" color="#9CA3AF" :size="48" />
        </view>
        <view class="prompt-title">请先登录</view>
        <view class="prompt-desc">登录后查看个人中心</view>
        <button class="login-btn" @click="goToLogin">立即登录</button>
      </view>
      
      <!-- 已登录状态 -->
      <view v-else>
        <!-- 用户信息卡片 -->
        <view class="user-card">
          <view class="user-avatar">
            <image 
              v-if="userInfo.avatar" 
              class="avatar-image" 
              :src="userInfo.avatar" 
              mode="aspectFill" 
            />
            <view v-else class="avatar-placeholder">
              <uni-icons type="person" color="#ffffff" :size="36" />
            </view>
          </view>
          <view class="user-info">
            <view class="user-name">{{ userInfo.nickname || userInfo.username || '用户' }}</view>
            <view class="user-phone">{{ userInfo.mobile || '未绑定手机' }}</view>
          </view>
          <view class="user-actions">
            <button class="edit-btn" @click="editProfile">
              <uni-icons type="compose" color="#007AFF" :size="24" />
            </button>
          </view>
        </view>
        
        <!-- 功能菜单 -->
        <view class="menu-section">
          <view class="menu-group">
            <view class="menu-title">订单管理</view>
            <view class="menu-list">
              <view class="menu-item" @click="goToOrders">
                <view class="menu-icon">
                  <uni-icons type="cart" color="#007AFF" :size="28" />
                </view>
                <view class="menu-text">我的订单</view>
                <view class="menu-arrow">
                  <uni-icons type="arrowright" color="#9CA3AF" :size="20" />
                </view>
              </view>
              
              <view class="menu-item" @click="goToFavorites">
                <view class="menu-icon">
                  <uni-icons type="heart" color="#FF6B6B" :size="28" />
                </view>
                <view class="menu-text">我的收藏</view>
                <view class="menu-arrow">
                  <uni-icons type="arrowright" color="#9CA3AF" :size="20" />
                </view>
              </view>
            </view>
          </view>
          
          <view class="menu-group">
            <view class="menu-title">账户设置</view>
            <view class="menu-list">
              <view class="menu-item" @click="goToSecurity">
                <view class="menu-icon">
                  <uni-icons type="locked" color="#FFD93D" :size="28" />
                </view>
                <view class="menu-text">安全设置</view>
                <view class="menu-arrow">
                  <uni-icons type="arrowright" color="#9CA3AF" :size="20" />
                </view>
              </view>
              
              <view class="menu-item" @click="goToFeedback">
                <view class="menu-icon">
                  <uni-icons type="chat" color="#6C5CE7" :size="28" />
                </view>
                <view class="menu-text">意见反馈</view>
                <view class="menu-arrow">
                  <uni-icons type="arrowright" color="#9CA3AF" :size="20" />
                </view>
              </view>
            </view>
          </view>
          
          <view class="menu-group">
            <view class="menu-title">关于我们</view>
            <view class="menu-list">
              <view class="menu-item" @click="goToAbout">
                <view class="menu-icon">
                  <uni-icons type="info" color="#A29BFE" :size="28" />
                </view>
                <view class="menu-text">关于应用</view>
                <view class="menu-arrow">
                  <uni-icons type="arrowright" color="#9CA3AF" :size="20" />
                </view>
              </view>
              
              <view class="menu-item" @click="contactUs">
                <view class="menu-icon">
                  <uni-icons type="phone" color="#55EFC4" :size="28" />
                </view>
                <view class="menu-text">联系我们</view>
                <view class="menu-arrow">
                  <uni-icons type="arrowright" color="#9CA3AF" :size="20" />
                </view>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 退出登录按钮 -->
        <view class="logout-section">
          <button class="logout-btn" @click="logout">退出登录</button>
        </view>
      </view>
    </view>
    
    
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
// #ifdef H5
 
// #endif

const uniIdCo = uniCloud.importObject('uni-id-co', { customUI: true })

const isLoggedIn = ref(false)
const userInfo = ref({})

// 检查登录状态
const checkLoginStatus = async () => {
  try {
    const token = uni.getStorageSync('uni_id_token')
    let tokenExpired = 0
    try {
      const info = uniCloud.getCurrentUserInfo()
      tokenExpired = info?.tokenExpired || 0
    } catch (e) {}
    if (!tokenExpired) {
      tokenExpired = Number(uni.getStorageSync('uni_id_token_expired') || 0)
    }
    const valid = !!token && Number(tokenExpired) > Date.now()
    isLoggedIn.value = valid
    if (valid) {
      loadUserInfo()
    } else {
      // 未登录时自动跳转至登录页，保持与小程序行为一致
      uni.redirectTo({
        url: '/uni_modules/uni-id-pages/pages/login/login-withpwd'
      })
    }
  } catch (error) {
    isLoggedIn.value = false
  }
}

// 加载用户信息
const loadUserInfo = async () => {
  try {
    // 首先尝试从 uniCloud 获取当前用户信息
    const userInfoFromCloud = uniCloud.getCurrentUserInfo()
    if (userInfoFromCloud && userInfoFromCloud.uid) {
      // 从 uni-id-users 集合获取用户的详细信息
      const db = uniCloud.database()
      const { result } = await db
        .collection('uni-id-users')
        .where('_id==$cloudEnv_uid')
        .field('username,nickname,mobile,email,avatar,avatar_file,wx_avatar')
        .get()
      
      let info = (result && result.data && result.data[0]) || {}
      
      // 处理头像：优先级 avatar_file.url > avatar > wx_avatar > userInfoFromCloud.avatar
      let avatarUrl = null
      
      if (info.avatar_file) {
        // avatar_file 是一个对象，包含 url 属性
        if (typeof info.avatar_file === 'object' && info.avatar_file.url) {
          avatarUrl = info.avatar_file.url
        }
      }
      
      if (!avatarUrl && info.avatar) {
        avatarUrl = info.avatar
      }
      
      if (!avatarUrl && info.wx_avatar) {
        avatarUrl = info.wx_avatar
      }
      
      if (!avatarUrl && userInfoFromCloud.avatar) {
        avatarUrl = userInfoFromCloud.avatar
      }
      
      if (avatarUrl) {
        info.avatar = avatarUrl
      }
      
      userInfo.value = info
    } else {
      throw new Error('无法获取用户信息')
    }
  } catch (err) {
    // 如果获取失败，尝试从本地存储获取
    try {
      const localUserInfo = uni.getStorageSync('uni_id_user_info')
      if (localUserInfo) {
        userInfo.value = localUserInfo
      }
    } catch (e) {
      // 最后的备选方案：使用空对象
      userInfo.value = {}
    }
  }
}

// 跳转到登录页
const goToLogin = () => {
  uni.navigateTo({
    url: '/uni_modules/uni-id-pages/pages/login/login-withpwd'
  })
}

// 编辑个人资料
const editProfile = () => {
  uni.navigateTo({
    url: '/uni_modules/uni-id-pages/pages/userinfo/userinfo'
  })
}

// 跳转到我的订单
const goToOrders = () => {
  uni.navigateTo({
    url: '/pages/ordered/ordered'
  })
}

// 跳转到我的收藏
const goToFavorites = () => {
  uni.navigateTo({
    url: '/pages/favorites/favorites'
  })
}

// 跳转到安全设置
const goToSecurity = () => {
  uni.navigateTo({
    url: '/uni_modules/uni-id-pages/pages/userinfo/set-pwd/set-pwd'
  })
}

// 跳转到意见反馈
const goToFeedback = () => {
  uni.showToast({
    title: '功能开发中',
    icon: 'none'
  })
}

// 跳转到关于应用
const goToAbout = () => {
  uni.showToast({
    title: '功能开发中',
    icon: 'none'
  })
}

// 联系我们
const contactUs = () => {
  uni.makePhoneCall({
    phoneNumber: '400-123-4567'
  })
}

// 退出登录
const logout = () => {
  uni.showModal({
    title: '确认退出',
    content: '确定要退出登录吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          // 调用退出登录接口
          await uniIdCo.logout()
          
          // 清除本地存储
          await uni.removeStorageSync('uni_id_token')
          await uni.removeStorageSync('uni_id_user_info')
          
          // 更新登录状态
          isLoggedIn.value = false
          userInfo.value = {}
          
          uni.showToast({
            title: '退出成功',
            icon: 'success'
          })
        } catch (err) {
          uni.showToast({
            title: '退出失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

onMounted(() => {
  checkLoginStatus()
})

onShow(() => {
  checkLoginStatus()
})
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background: #f8fafc;
  padding-bottom: 100rpx;
}

.content {
  padding: 32rpx;
}

/* 登录提示样式 */
.login-prompt {
  text-align: center;
  padding: 120rpx 32rpx;
  background: #ffffff;
  border-radius: 16rpx;
  margin-top: 32rpx;
}

.prompt-icon {
  margin-bottom: 24rpx;
}

.prompt-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #374151;
  margin-bottom: 16rpx;
}

.prompt-desc {
  font-size: 26rpx;
  color: #6B7280;
  margin-bottom: 48rpx;
}

.login-btn {
  background: #007AFF;
  color: #ffffff;
  border: none;
  border-radius: 12rpx;
  padding: 24rpx 48rpx;
  font-size: 28rpx;
  font-weight: 600;
}

/* 用户信息卡片样式 */
.user-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 20rpx;
  padding: 48rpx 32rpx;
  margin-bottom: 32rpx;
  display: flex;
  align-items: center;
  color: #ffffff;
  box-shadow: 0 12rpx 40rpx rgba(102, 126, 234, 0.3);
}

.user-avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 24rpx;
  border: 4rpx solid rgba(255, 255, 255, 0.3);
}

.avatar-image {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
}

.user-info {
  flex: 1;
}

.user-name {
  font-size: 36rpx;
  font-weight: 700;
  margin-bottom: 8rpx;
}

.user-phone {
  font-size: 26rpx;
  opacity: 0.9;
}

.user-actions {
  margin-left: auto;
}

.edit-btn {
  background: rgba(255, 255, 255, 0.2);
  border: none;
  border-radius: 50%;
  width: 64rpx;
  height: 64rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 菜单区域样式 */
.menu-section {
  margin-bottom: 32rpx;
}

.menu-group {
  background: #ffffff;
  border-radius: 16rpx;
  margin-bottom: 24rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.menu-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #374151;
  padding: 24rpx 32rpx 16rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.menu-list {
  padding: 0;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 24rpx 32rpx;
  border-bottom: 1rpx solid #f8f8f8;
  transition: background-color 0.2s ease;
  
  &:last-child {
    border-bottom: none;
  }
  
  &:active {
    background-color: #f8fafc;
  }
}

.menu-icon {
  margin-right: 20rpx;
  width: 48rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.menu-text {
  flex: 1;
  font-size: 28rpx;
  color: #374151;
}

.menu-arrow {
  margin-left: auto;
}

/* 退出登录按钮样式 */
.logout-section {
  padding: 0 32rpx;
}

.logout-btn {
  width: 100%;
  background: #ffffff;
  color: #EF4444;
  border: 1rpx solid #EF4444;
  border-radius: 12rpx;
  padding: 24rpx;
  font-size: 28rpx;
  font-weight: 600;
  
  &:active {
    background: #FEF2F2;
  }
}
</style>